package com.lagou;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 独立数据库的自增ID
 */
public class GlobalIdGenerator {

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println("序号: " + i + " 自增主键 = " + getKey());
        }
    }

    public static String getKey(){
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        String id = "";
        try {
            // 加载数据库驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 通过驱动管理类获取数据库链接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?characterEncoding=utf-8","root","root");
            // 这里的createtime字段无实际意义，是为了随便插⼊一条数据以获取自增id
            String insertSql = "insert into distribute_id(createtime) values(now())";
            // 获取预处理statement
            preparedStatement = connection.prepareStatement(insertSql);
            // 向数据库发出sql执⾏查询，查询出结果集
            preparedStatement.executeUpdate();
            // 定义sql语句？表示占位符persistence
            String selectsql = "select LAST_INSERT_ID()  as ID";
            // 获取预处理statement
            preparedStatement = connection.prepareStatement(selectsql);
            // 向数据库发出sql执行查询，查询出结果集
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                id = resultSet.getString("ID");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closResource(resultSet, preparedStatement, connection);
        }
        return id;
    }

    /**
     * 关闭资源
     */
    private static void closResource(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {
        // 释放资源
        if (resultSet != null) {
            try{
                resultSet.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (preparedStatement != null) {
            try{
                preparedStatement.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try{
                connection.close();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
